﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace deFramework.BusinessRules
{
    public class SpBlogTools: Base.BaseBusinessRule
    {
        #region "Constructor, private Variables"
		
        /// <summary>
        /// 
        /// </summary>
        /// <param name="aContext"></param>
        public SpBlogTools(ref Common.PresentationContext aContext) : base(ref aContext) { }  
 
 
		#endregion

        #region "Public - SubmitBlogComment, GetPostsWithCommentsAsXml" 

        public bool SubmitBlogComment(string blogUrl, string nameCommentsList, string namePostsList,
          string title, int topicID, string comments, string statusFieldName, string initStatus)
        {
            bool _result = false;
            string placeCode = "1";
            Microsoft.SharePoint.SPWeb webDefault = this.MyContext.MySpWeb;
            try
            {
                this.MyContext.MySpWeb = this.GetSpWeb(blogUrl);
                Microsoft.SharePoint.SPWeb objectWeb = this.MyContext.MySpWeb;
                Microsoft.SharePoint.SPSite siteColl = objectWeb.Site;
                Microsoft.SharePoint.SPWeb siteWeb = objectWeb;
                placeCode = "2";
                Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (Microsoft.SharePoint.SPSite elevatedsiteColl = new Microsoft.SharePoint.SPSite(siteColl.ID))
                    {
                        using (Microsoft.SharePoint.SPWeb elevatedSite = elevatedsiteColl.OpenWeb(siteWeb.ID))
                        {
                            try
                            {
                                placeCode = "3";
                                this.MyContext.MySpWeb = elevatedSite;
                                this.MyContext.MySpWeb.AllowUnsafeUpdates = true;
                                placeCode = "4";
                                Microsoft.SharePoint.SPList listObject = elevatedSite.Lists[nameCommentsList];
                                _result = this.AddItemtoCommentsList(ref placeCode, ref listObject,
                                    namePostsList, title, topicID, comments, statusFieldName, initStatus);
                            }
                            catch (Exception ex)
                            {
                                Exception throwUp = new Exception("placeCode=" + placeCode + "; " + ex.Message, ex);
                                this.CurrentException = throwUp;
                            }
                            finally
                            {
                                this.MyContext.MySpWeb.AllowUnsafeUpdates = false;
                                this.MyContext.MySpWeb.Dispose();
                                this.MyContext.MySpWeb = objectWeb;
                            }
                        }
                    }
                });

            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            finally
            {
                Microsoft.SharePoint.SPWeb tempWeb = this.MyContext.MySpWeb;
                tempWeb.Dispose();
                this.MyContext.MySpWeb = webDefault;
            }
            return _result;
        }

  
        public string GetPostsWithCommentsAsXml(string blogUrl, string namePostsList, string nameCommentsList,
        string postCriteriaField, string postCriteriaValue, string commCriteriaField, string commCriteriaValue)
        {
            string _result = String.Empty;
            string placeCode = "1";
            Microsoft.SharePoint.SPWeb webDefault = this.MyContext.MySpWeb;
            try
            {
                this.MyContext.MySpWeb = this.GetSpWeb(blogUrl); 
                this.SetParams_PostsWithCommentsAsXml(blogUrl, namePostsList, nameCommentsList,
                    postCriteriaField, postCriteriaValue, commCriteriaField, commCriteriaValue);
                Microsoft.SharePoint.SPWeb objectWeb = this.MyContext.MySpWeb;
                Microsoft.SharePoint.SPSite siteColl = objectWeb.Site;
                Microsoft.SharePoint.SPWeb siteWeb = objectWeb;
                placeCode = "2";
                Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (Microsoft.SharePoint.SPSite elevatedsiteColl = new Microsoft.SharePoint.SPSite(siteColl.ID))
                    {
                        using (Microsoft.SharePoint.SPWeb elevatedSite = elevatedsiteColl.OpenWeb(siteWeb.ID))
                        {
                            try
                            {
                                placeCode = "3";
                                this.MyContext.MySpWeb = elevatedSite;
                                this.MyContext.MySpWeb.AllowUnsafeUpdates = true;
                                placeCode = "4";
                                System.Data.DataTable tablePosts = this.GetPostsAsDataTable(
                                    this.Param_NamePostsList, this.Param_PostCriteriaField, this.Param_PostCriteriaValue);
                                placeCode = "5";
                                System.Data.DataTable tableComments = this.GetCommentsAsDataTable(
                                    this.Param_NameCommentsList, this.Param_CommCriteriaField, this.Param_CommCriteriaValue);
                                placeCode = "6";
                                string xml = this.BlogXml(tablePosts, tableComments);
                                xml = deFramework.Common.DotNetUtilities.Base64Encode(xml); 
                                // object xml = this.ElevatedSharePointProcessing(new MethodNoParameters(
                                //string xml = this.Details_PostsWithCommentsAsXml();
                                placeCode = "7";
                                string kAllTopicsXml = "{0}<Blog>{1}</Blog>";
                                string kXmlPrefix = ""; //<?xml version=\"1.0\" encoding=\"utf-16\"?>";
                                _result = String.Format(kAllTopicsXml, kXmlPrefix, xml); //.ToString());
                            }
                            catch (Exception ex)
                            {
                                Exception throwUp = new Exception("placeCode=" + placeCode + "; " + ex.Message, ex);
                                this.CurrentException = throwUp;
                            }
                            finally
                            {
                                this.MyContext.MySpWeb.AllowUnsafeUpdates = false;
                                this.MyContext.MySpWeb.Dispose();
                                this.MyContext.MySpWeb = objectWeb;
                            }
                        }
                    }
                });

            }
            catch (Exception ex)
            {
                Exception throwUp = new Exception("placeCode=" + placeCode + "; " + ex.Message, ex);
                this.CurrentException = throwUp;
            }
            finally
            {
                Microsoft.SharePoint.SPWeb tempWeb = this.MyContext.MySpWeb;
                tempWeb.Dispose();
                this.MyContext.MySpWeb = webDefault;
            }
            return _result;
        }

   
        //    catch (Exception ex)
        //    {
        //        Exception throwUp = new Exception("placeCode=" + placeCode + "; " + ex.Message, ex);
        //        this.CurrentException = throwUp;
        //    }
        //    finally
        //    {
        //        Microsoft.SharePoint.SPWeb tempWeb = this.MyContext.MySpWeb;
        //        tempWeb.Dispose();
        //        this.MyContext.MySpWeb = webDefault;
        //    }
        //    return _result; 
        //}






        #endregion 

        #region "SubmitBlogComment subs - AddItemtoCommentsList, PostReferenceForComment"

        private bool AddItemtoCommentsList(ref string placeCode, ref Microsoft.SharePoint.SPList listObject, string namePostsList,
            string title, int topicID, string comments, string statusFieldName, string initStatus)
        {

            if (System.Web.HttpContext.Current != null)
            {
                if (System.Web.HttpContext.Current.Items["HttpHandlerSPWeb"] == null)
                    System.Web.HttpContext.Current.Items["HttpHandlerSPWeb"] = this.MyContext.MySpWeb;
            }
            placeCode = "5"; 
            Microsoft.SharePoint.SPListItem itemObject = listObject.Items.Add();

            placeCode = "6";
            itemObject["Title"] = title;
            itemObject["Body"] = comments;
            placeCode = "7";
            itemObject[statusFieldName] = initStatus; // "External";
            placeCode = "8; status=" + initStatus;
            Microsoft.SharePoint.SPFieldLookupValue objRef = this.PostReferenceForComment(
                topicID, namePostsList, ref placeCode);
            placeCode = "9; " + placeCode; 
            itemObject["Post Title"] = objRef;
            placeCode = "10";
            itemObject.Update();
            placeCode = "11"; 
            placeCode = "12"; 
            
            return true;
        }



        private Microsoft.SharePoint.SPFieldLookupValue PostReferenceForComment(
             int topicID, string namePostsList, ref string placeCode)
        {
            Microsoft.SharePoint.SPFieldLookupValue _result = null; 
            string topicTitle = String.Empty;
            Microsoft.SharePoint.SPList listPosts =
                    this.MyContext.MySpWeb.Lists[namePostsList];
            placeCode += "; topicID=" + topicID.ToString()+";"; 
            foreach (Microsoft.SharePoint.SPListItem item in listPosts.Items)
            {
                placeCode += item.ID.ToString();
                if (item.ID == topicID)
                {
                    placeCode += "(";
                    _result = new Microsoft.SharePoint.SPFieldLookupValue(item.ID, item.Title);
                    placeCode += ")" + _result.LookupValue + ".";
                    break;
                }
                else
                    placeCode += "."; 
            }
            return _result;
        }


        #endregion

        #region "GetPostsWithCommentsAsXml Variables + Subs - SetParams_PostsWithCommentsAsXml, Details_PostsWithCommentsAsXml"

        #region "Variables"

        private string Param_BlogUrl = String.Empty;
        private string Param_NamePostsList = String.Empty;
        private string Param_NameCommentsList = String.Empty;
        private string Param_PostCriteriaField = String.Empty;
        private string Param_PostCriteriaValue = String.Empty;
        private string Param_CommCriteriaField = String.Empty;
        private string Param_CommCriteriaValue = String.Empty;

        #endregion 

        
        private void SetParams_PostsWithCommentsAsXml(string blogUrl, string namePostsList, string nameCommentsList,
                string postCriteriaField, string postCriteriaValue, string commCriteriaField, string commCriteriaValue)
        {
            this.Param_BlogUrl = blogUrl;
            this.Param_NamePostsList = namePostsList;
            this.Param_NameCommentsList = nameCommentsList;

            this.Param_PostCriteriaField = postCriteriaField;
            this.Param_PostCriteriaValue = postCriteriaValue;
            this.Param_CommCriteriaField = commCriteriaField;
            this.Param_CommCriteriaValue = commCriteriaValue;
        }


        //private string Details_PostsWithCommentsAsXml()
        //{
        //    System.Data.DataTable tablePosts = this.GetPostsAsDataTable(
        //        this.Param_NamePostsList, this.Param_PostCriteriaField, this.Param_PostCriteriaValue);
        //    System.Data.DataTable tableComments = this.GetCommentsAsDataTable(
        //        this.Param_NameCommentsList, this.Param_CommCriteriaField, this.Param_CommCriteriaValue);
        //    string xml = this.BlogXml(tablePosts, tableComments);
        //    return xml;
        //}

        #endregion 

        #region "GetPostsWithCommentsAsXml subs - GetPostsAsDataTable, GetCommentsAsDataTable, BlogXml, PostComments"


        private System.Data.DataTable GetPostsAsDataTable(string namePostsList, string criteriaField, string criteriaValue)
        {
            string kCaml1 = "<Where><Eq><FieldRef Name=\"{0}\" /><Value ";
            string kCaml2 = "Type=\"Choice\">{1}</Value></Eq></Where>";
            string caml = String.Format(kCaml1 + kCaml2, criteriaField, criteriaValue);
            this.DebugCamlPosts = "<PostsListName>" + namePostsList + "</PostsListName><PostsCaml>" + caml + "</PostsCaml>";
            return this.GetListCamlResultsAsDataTable(namePostsList, caml);
        }

        private string DebugCamlPosts = String.Empty; 

        private System.Data.DataTable GetCommentsAsDataTable(string nameCommentsList, string criteriaField, string criteriaValue)
        {
            string kCaml1 = "<Where><Eq><FieldRef Name=\"{0}\" /><Value ";
            string kCaml2 = "Type=\"Choice\">{1}</Value></Eq></Where>";
            string caml = String.Format(kCaml1 + kCaml2, criteriaField, criteriaValue);
            this.DebugCamlComments = "<CommentsListName>" + nameCommentsList + "</CommentsListName><CommentsCaml>" + caml + "</CommentsCaml>"; 
            return this.GetListCamlResultsAsDataTable(nameCommentsList, caml);
        }

        private string DebugCamlComments = String.Empty;



        private string PostBodyCleanupForExport(string rawBody)
        {
            int _count = 0;
            string _string = rawBody.Trim();
            while (this.StringIsDivTag(_count, _string))
            {
                _count += 1;
                int posDelim = _string.IndexOf(">");
                int lenNewString = _string.Length - 7 - posDelim;
                _string = _string.Substring(posDelim + 1, lenNewString).Trim();
            }
            return _string; 
        }

        private bool StringIsDivTag(int aCounter, string aString)
        {
            string upperTrim = aString.Trim().ToUpper();
            return (aCounter < 10 && upperTrim.StartsWith("<DIV") && upperTrim.EndsWith("</DIV>"));
        }


         
        private string BlogXml(System.Data.DataTable objTable, System.Data.DataTable tableComments)
        {
            string xml = String.Empty;
            if (this.MyContext.ConfigAppSettingValue("DebugMode", "N").ToUpper().Trim().StartsWith("Y"))
            {
                xml += this.DebugCamlComments + this.DebugCamlPosts;
                xml += "<countposts>" + objTable.Rows.Count.ToString() + "</countposts>";
                xml += "<countcomms>" + tableComments.Rows.Count.ToString() + "</countcomms>";
            }
                foreach (System.Data.DataRow row in objTable.Rows)
            {
                try
                {
                    string kTopicNode = "<Topic ID=\"{0}\" Title=\"{1}\" Created=\"{2}\"><Body>{3}</Body>{4}</Topic>";
                    string dateStr = row["Created"].ToString(); // String.Format("11/1{0}/2009", "2");
                    string title = row["Title"].ToString(); //System.Web.HttpUtility.UrlEncode(  String.Format("Title <B>Number</B> {0} and Blog Example {0}", "2"));
                    string body = row["Body"].ToString();
                    body = this.PostBodyCleanupForExport(body); 
                    string id = row["ID"].ToString();
                    string comments = this.PostComments(id, tableComments);
                    string nodeTopic = String.Format(kTopicNode, id, title, dateStr, body, comments);
                    xml += nodeTopic;
                }
                catch (Exception ex)
                {
                    this.CurrentException = ex;
                }
            }
           
            return xml;
        }


        private string PostComments(string postId, System.Data.DataTable tableComments)
        {
            string xml = String.Empty; // "<Comments></Comments>";
            string kCommentNode = "<Comment Title=\"{0}\" Created=\"{1}\">{2}</Comment>";
            foreach (System.Data.DataRow row in tableComments.Rows)
            {
                string commentPostID = row["PostID"].ToString();
                if (commentPostID == postId)
                {
                    string dateStr = Convert.ToDateTime(row["Created"]).ToString("MM/dd/yyyy");
                    string title = row["Title"].ToString(); //System.Web.HttpUtility.UrlEncode(
                    string body = row["Body"].ToString(); //System.Web.HttpUtility.UrlEncode(
                    xml += String.Format(kCommentNode, title, dateStr, body);
                }
            }
            return xml;
        }

        #endregion

        #region "Reusable - UtahSpDataAccess, OpenSiteAsSpWeb, SpListCamlResultsAsTable, GetListCamlResultsAsDataTable, SpListCamlQueryResults"

        private deFramework.Base.BaseSharePointDataAccess BaseSpDataAccessObject()
        {
            Microsoft.SharePoint.SPWeb objectWeb = this.MySpWeb;
            deFramework.Base.BaseSharePointDataAccess objectDataAccess
                = new deFramework.Base.BaseSharePointDataAccess(ref objectWeb);
            return objectDataAccess;
        }


        protected System.Data.DataTable SpListCamlResultsAsTable(
                Microsoft.SharePoint.SPList listQuery, string camlQuery)
        {
            return this.SpListCamlQueryResults(listQuery, camlQuery).GetDataTable();
        }


        protected System.Data.DataTable GetListCamlResultsAsDataTable(string listName, string caml)
        {
            System.Data.DataTable resultTable = null;
            try
            {
                Microsoft.SharePoint.SPList listObject = this.MyContext.MySpWeb.Lists[listName];
                resultTable = this.SpListCamlQueryResults(listObject, caml).GetDataTable();
            }
            catch (Exception ex)
            {
                Exception myEx = new Exception(ex.Message + "; listName=" + listName + "; caml = " + caml, ex);
                throw myEx; 
            }
            return resultTable;
        }

        /// <summary>
        /// Returns a SPListItemCollection for a particular SPList and a CAML query.
        /// </summary>
        /// <param name="listQuery">the particular SPList to use for the CAML query</param>
        /// <param name="camlQuery"></param>
        /// <returns></returns>
        protected Microsoft.SharePoint.SPListItemCollection SpListCamlQueryResults(
            Microsoft.SharePoint.SPList listQuery, string camlQuery)
        {
            deFramework.Base.BaseSharePointDataAccess da = this.BaseSpDataAccessObject();
            return da.SpListCamlQueryResults(listQuery, camlQuery);
        }


        #endregion

        #region "Obsolete Code" 

        [Obsolete]
        public string OLD_GetPostsWithCommentsAsXml(string blogUrl, string namePostsList, string nameCommentsList,
                string postCriteriaField, string postCriteriaValue, string commCriteriaField, string commCriteriaValue)
        {
            string _result = String.Empty;
            Microsoft.SharePoint.SPWeb webDefault = this.MyContext.MySpWeb;
            try
            {
                this.MyContext.MySpWeb = this.GetSpWeb(blogUrl);
                Microsoft.SharePoint.SPSite siteColl = this.MyContext.MySpWeb.Site;
                Microsoft.SharePoint.SPWeb siteWeb = this.MyContext.MySpWeb;
                Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (Microsoft.SharePoint.SPSite elevatedsiteColl = new Microsoft.SharePoint.SPSite(siteColl.ID))
                    {
                        using (Microsoft.SharePoint.SPWeb elevatedSite = elevatedsiteColl.OpenWeb(siteWeb.ID))
                        {
                            try
                            {
                                this.MyContext.MySpWeb = elevatedSite;
                                System.Data.DataTable tablePosts = this.GetPostsAsDataTable(namePostsList, postCriteriaField, postCriteriaValue);
                                System.Data.DataTable tableComments = this.GetCommentsAsDataTable(nameCommentsList, commCriteriaField, commCriteriaValue);
                                //this.dataGridView1.DataSource = tableComments; 
                                _result = this.BlogXml(tablePosts, tableComments);
                            }
                            catch (Exception ex)
                            {
                                this.CurrentException = ex;
                            }
                            //finally
                            //{
                            //    this.MyContext.MySpWeb = objectWeb;
                            //}
                        }
                    }
                });

            }
            catch (Exception ex)
            {
                this.CurrentException = ex;
            }
            finally
            {
                Microsoft.SharePoint.SPWeb tempWeb = this.MyContext.MySpWeb;
                tempWeb.Dispose();
                this.MyContext.MySpWeb = webDefault;
            }
            string kAllTopicsXml = "{0}<Blog>{1}</Blog>";
            string kXmlPrefix = "<?xml version=\"1.0\" encoding=\"utf-16\"?>";
            _result = String.Format(kAllTopicsXml, kXmlPrefix, _result);
            return _result;
        }



        #endregion

    }
}

#region "Dead Code" 

//Microsoft.Office.Server.ServerContext context = Microsoft.Office.Server.ServerContext.GetContext(
//    this.MyContext.MySpWeb);

//if (System.Web.HttpContext.Current.Items["Microsoft.Office.ServerContext"] == null)      
//    System.Web.HttpContext.Current.Items["Microsoft.Office.ServerContext"] = 
//        this.

//        ServerContext.Default;}

//this.MyContext.MySpWeb.AllowUnsafeUpdates = false;

//string kAllTopicsXml = "{0}<Blog>{1}</Blog>";
// String.Format(kAllTopicsXml, "<?xml version=\"1.0\" encoding=\"utf-16\"?>", xml);


#endregion 
